package com.srmt.document.examples;

import com.lark.oapi.service.docx.v1.model.Block;
import com.lark.oapi.service.docx.v1.model.Sheet;
import com.srmt.document.exception.DocumentOperationException;
import com.srmt.document.exception.TableException;
import com.srmt.document.feishu.internal.core.BlockContext;
import com.srmt.document.feishu.internal.core.BlockUtils;
import com.srmt.document.feishu.internal.table.TableStrategyFactory;
import com.srmt.document.feishu.internal.table.TableOperationStrategy;
import com.srmt.document.feishu.internal.table.model.TableContext;
import com.srmt.document.feishu.internal.table.model.TableType;
import com.srmt.feishu.client.FeishuClient;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电子表格操作示例代码
 * 
 * 展示如何使用SheetStrategy处理文档中的电子表格（blockType=30）
 * 
 * @author srmt
 * @since 3.0.0
 */
public class SheetOperationExample {
    
    /**
     * 示例1：创建电子表格Block
     */
    public static void createSheetExample(FeishuClient client) throws TableException {
        // 创建策略工厂
        TableStrategyFactory factory = TableStrategyFactory.create(client);
        
        // 获取Sheet策略
        TableOperationStrategy strategy = factory.getStrategy(TableType.SHEET);
        
        // 准备初始数据
        List<List<String>> content = Arrays.asList(
            Arrays.asList("产品名称", "销售量", "单价", "总价"),
            Arrays.asList("产品A", "100", "50.00", "=B2*C2"),
            Arrays.asList("产品B", "200", "30.00", "=B3*C3"),
            Arrays.asList("产品C", "150", "45.00", "=B4*C4"),
            Arrays.asList("合计", "=SUM(B2:B4)", "", "=SUM(D2:D4)")
        );
        
        // 创建5x4的电子表格结构
        Block[] blocks = strategy.createTableStructure(5, 4, content);
        
        // 输出创建的Block信息
        for (Block block : blocks) {
            System.out.println("Created block: " + block.getBlockId() + 
                             " (type: " + block.getBlockType() + ")");
        }
    }
    
    /**
     * 示例2：识别和处理不同类型的表格Block
     */
    public static void identifyTableTypeExample(FeishuClient client, String documentId) 
            throws Exception {
        
        // 创建Block上下文
        BlockContext blockContext = new BlockContext(client, documentId);
        
        // 获取文档中的所有Block
        List<Block> blocks = blockContext.getBlocks();
        
        // 创建策略工厂
        TableStrategyFactory factory = TableStrategyFactory.create(client);
        
        for (Block block : blocks) {
            if (BlockUtils.isTableBlock(block)) {
                Integer blockType = block.getBlockType();
                
                // 根据blockType识别表格类型
                switch (blockType) {
                    case BlockUtils.BLOCK_TYPE_TABLE:  // 31
                        System.out.println("Found normal table: " + block.getBlockId());
                        handleNormalTable(factory, blockContext, block);
                        break;
                        
                    case BlockUtils.BLOCK_TYPE_SHEET:  // 30
                        System.out.println("Found sheet: " + block.getBlockId());
                        handleSheet(factory, blockContext, block);
                        break;
                        
                    case BlockUtils.BLOCK_TYPE_BITABLE: // 18
                        System.out.println("Found bitable: " + block.getBlockId());
                        handleBitable(factory, blockContext, block);
                        break;
                        
                    default:
                        System.out.println("Unknown table type: " + blockType);
                }
            }
        }
    }
    
    /**
     * 处理普通表格
     */
    private static void handleNormalTable(TableStrategyFactory factory, 
                                         BlockContext blockContext, 
                                         Block tableBlock) throws TableException {
        TableOperationStrategy strategy = factory.getStrategy(TableType.NORMAL_TABLE);
        TableContext context = new TableContext("", blockContext, tableBlock);
        
        // 获取表格维度
        int[] dimensions = strategy.getTableDimensions(context);
        System.out.println("  Normal table dimensions: " + 
                         dimensions[0] + " rows x " + dimensions[1] + " columns");
        
        // 普通表格的数据存储在Block结构中
        System.out.println("  Data stored in block structure");
    }
    
    /**
     * 处理电子表格
     */
    private static void handleSheet(TableStrategyFactory factory, 
                                   BlockContext blockContext, 
                                   Block sheetBlock) throws TableException {
        TableOperationStrategy strategy = factory.getStrategy(TableType.SHEET);
        TableContext context = new TableContext("", blockContext, sheetBlock);
        
        // 获取Sheet对象
        Sheet sheet = sheetBlock.getSheet();
        if (sheet != null) {
            System.out.println("  Sheet token: " + sheet.getToken());
            System.out.println("  Sheet dimensions: " + 
                             sheet.getRowSize() + " rows x " + 
                             sheet.getColumnSize() + " columns");
            
            // 电子表格的数据存储在外部电子表格文档中
            System.out.println("  Data stored in external spreadsheet document");
            
            // 可以通过Sheets API进行更多操作
            System.out.println("  Supports formulas, charts, filters, etc.");
        }
    }
    
    /**
     * 处理多维表格
     */
    private static void handleBitable(TableStrategyFactory factory, 
                                     BlockContext blockContext, 
                                     Block bitableBlock) throws TableException {
        TableOperationStrategy strategy = factory.getStrategy(TableType.BITABLE);
        TableContext context = new TableContext("", blockContext, bitableBlock);
        
        // 获取Bitable对象
        if (bitableBlock.getBitable() != null) {
            System.out.println("  Bitable token: " + bitableBlock.getBitable().getToken());
            
            // 多维表格的数据存储在外部多维表格应用中
            System.out.println("  Data stored in external bitable application");
            
            // 可以通过Bitable API进行数据库式操作
            System.out.println("  Supports database-like operations");
        }
    }
    
    /**
     * 示例3：电子表格单元格操作
     */
    public static void sheetCellOperationExample(FeishuClient client, 
                                                 String documentId, 
                                                 String sheetBlockId) throws TableException, DocumentOperationException {
        
        // 创建Block上下文
        BlockContext blockContext = new BlockContext(client, documentId);
        
        // 获取Sheet Block
        Block sheetBlock = blockContext.getBlockById(sheetBlockId);
        
        // 创建策略工厂和获取策略
        TableStrategyFactory factory = TableStrategyFactory.create(client);
        TableOperationStrategy strategy = factory.getStrategy(TableType.SHEET);
        
        // 创建表格上下文
        TableContext context = new TableContext(documentId, blockContext, sheetBlock);
        
        // 定位单元格（使用A1表示法）
        String cellAddress = strategy.locateTableCell(context, 0, 0);  // A1
        System.out.println("Cell [0,0] address: " + cellAddress);
        
        cellAddress = strategy.locateTableCell(context, 2, 3);  // D3
        System.out.println("Cell [2,3] address: " + cellAddress);
        
        // 批量更新单元格
        Map<String, String> updates = new HashMap<>();
        updates.put("A1", "标题");
        updates.put("B1", "数值");
        updates.put("C1", "公式");
        updates.put("D1", "结果");
        
        // 注意：实际更新需要使用 batchUpdateCellsByIndex 方法
        // 这里的示例仅展示数据准备
    }
    
    /**
     * 示例4：演示三种表格类型的区别
     */
    public static void demonstrateTableDifferences() {
        System.out.println("=== 飞书文档中的三种表格类型 ===\n");
        
        System.out.println("1. 普通表格 (Table, blockType=31)");
        System.out.println("   - 简单的表格结构");
        System.out.println("   - 数据存储在文档Block中");
        System.out.println("   - 支持基本的文本和格式");
        System.out.println("   - 适用于简单的数据展示\n");
        
        System.out.println("2. 电子表格 (Sheet, blockType=30)");
        System.out.println("   - 功能丰富的电子表格");
        System.out.println("   - 数据存储在外部电子表格文档");
        System.out.println("   - 支持公式、图表、筛选、排序");
        System.out.println("   - 使用A1表示法定位单元格");
        System.out.println("   - 适用于数据分析和计算\n");
        
        System.out.println("3. 多维表格 (Bitable, blockType=18)");
        System.out.println("   - 数据库式的表格应用");
        System.out.println("   - 数据存储在外部多维表格应用");
        System.out.println("   - 支持多视图、关联、自动化");
        System.out.println("   - 适用于项目管理和数据管理\n");
    }
    
    public static void main(String[] args) {
        // 演示表格类型的区别
        demonstrateTableDifferences();
        
        // 注意：以下示例需要实际的FeishuClient实例
        // FeishuClient client = new FeishuClient(...);
        
        // 示例1：创建电子表格
        // createSheetExample(client);
        
        // 示例2：识别表格类型
        // identifyTableTypeExample(client, "documentId");
        
        // 示例3：电子表格操作
        // sheetCellOperationExample(client, "documentId", "sheetBlockId");
    }
}